﻿/*
Copyright (c) 2011 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.Collections.Generic;
using System.Reflection;
using BlammoNet.Interfaces;
using Utilities.DataTypes.Patterns.BaseClasses;
using Utilities.Events.EventArgs;
#endregion

namespace EchoNet
{
    /// <summary>
    /// Manager for the task scheduler
    /// </summary>
    public class Manager : Singleton<Manager>
    {
        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        protected Manager()
            : base()
        {
            Config = Gestalt.Manager.Instance.GetConfigFile<Configuration.Configuration>("TaskScheduler");
            Workers = new List<Worker>();
            for (int x = 0; x < Config.NumberOfThreads; ++x)
            {
                Worker TempWorker = new Worker("");
                TempWorker.Finished = new EventHandler<OnEndEventArgs>(Finished);
                TempWorker.Started = new EventHandler<OnStartEventArgs>(Started);
                TempWorker.Exception = new EventHandler<OnErrorEventArgs>(Error);
                Workers.Add(TempWorker);
            }
        }

        #endregion

        #region Public Functions

        /// <summary>
        /// Starts the task manager
        /// </summary>
        /// <param name="TaskAssemblyLocation">Location of the task assembly</param>
        /// <param name="Log">Log using (if null, it uses its own default)</param>
        public void Start(string TaskAssemblyLocation, ILog Log = null)
        {
            Manager.Log = GetLog(Log);
            Assembly TaskAssembly = Assembly.LoadFile(TaskAssemblyLocation);
            AddTasks(TaskAssembly);
            StartWorkers();
        }

        /// <summary>
        /// Starts the task manager
        /// </summary>
        /// <param name="TaskAssembly">The task assembly</param>
        /// <param name="Log">Log using (if null, it uses its own default)</param>
        public void Start(Assembly TaskAssembly, ILog Log = null)
        {
            Manager.Log = GetLog(Log);
            AddTasks(TaskAssembly);
            StartWorkers();
        }

        /// <summary>
        /// Starts the task manager
        /// </summary>
        /// <param name="TaskAssemblies">The task assemblies</param>
        /// <param name="Log">Log using (if null, it uses its own default)</param>
        public void Start(List<Assembly> TaskAssemblies, ILog Log = null)
        {
            Manager.Log = GetLog(Log);
            for (int x = 0; x < TaskAssemblies.Count; ++x)
            {
                AddTasks(TaskAssemblies[x]);
            }
            StartWorkers();
        }

        /// <summary>
        /// Stops the tasks
        /// </summary>
        public void Stop()
        {
            for (int x = 0; x < Config.NumberOfThreads; ++x)
            {
                Workers[x].Stop();
            }
        }

        #endregion

        #region Private Functions

        private ILog GetLog(ILog Log)
        {
            if (Log == null)
            {
                Log = BlammoNet.Manager.Instance.GetLog("EchoNet");
            }
            return Log;
        }

        private void AddTasks(Assembly TaskAssembly)
        {
            List<Type> TaskTypes = Utilities.Reflection.Reflection.GetTypes(TaskAssembly, "EchoNet.Task");
            for (int x = 0; x < TaskTypes.Count; )
            {
                for (int y = 0; y < Workers.Count && x < TaskTypes.Count; ++y, ++x)
                {
                    Task TempTask = (Task)TaskTypes[x].Assembly.CreateInstance(TaskTypes[x].FullName);
                    TempTask.Setup(TaskTypes[x].Name);
                    Workers[y].AddTask(TempTask);
                }
            }
        }

        private void StartWorkers()
        {
            for (int x = 0; x < Config.NumberOfThreads; ++x)
            {
                Workers[x].Start();
            }
        }

        #endregion

        #region Private Properties

        private List<Worker> Workers { get; set; }
        private Configuration.Configuration Config { get; set; }
        private static ILog Log { get; set; }

        #endregion

        #region Event Handlers

        internal static void Finished(object sender, OnEndEventArgs e)
        {
            lock (Log)
            {
                Log.LogMessage("Worker finished", BlammoNet.Enum.MessageType.General);
            }
        }

        internal static void Started(object sender, OnStartEventArgs e)
        {
            lock (Log)
            {
                Log.LogMessage("Worker started", BlammoNet.Enum.MessageType.General);
            }
        }

        internal static void Error(object sender, OnErrorEventArgs e)
        {
            Exception Temp = (Exception)e.Content;
            lock (Log)
            {
                Log.LogMessage("Worker had the following error : {0}", BlammoNet.Enum.MessageType.Error, Temp.ToString());
            }
        }

        #endregion
    }
}